<template>
  <div class="app-container" style="height: 100%">
    <div
      class="app-container-inner"
      style="display: flex; flex-direction: column; flex: 1"
      v-loading="loading"
      element-loading-text="加载中..."
      v-if="isMounted"
    >
      <div class="main">
        <el-aside width="250px">
          <div class="nav">
            <div style="display: flex; gap: 5px; justify-content: flex-end">
              <HPlainButton v-show="notAllow == false" @click="editOrganize">部门编辑</HPlainButton>
              <HPlainButton @click="addOrganize">新增部门</HPlainButton>
            </div>
            <el-tree
              v-if="trees.length > 0"
              class="tree"
              :data="trees"
              :props="defaultProps"
              :highlight-current="true"
              :accordion="true"
              default-expand-all
              node-key="id"
              :current-node-key="defaultKey"
              @node-click="handleNodeClick"
            />
          </div>
        </el-aside>
        <el-main class="table-organize">
          <div class="header flex-justify-between">
            <div class="btns">
              <HPlainButton @click="addEmp">新增职员</HPlainButton>
            </div>
            <div class="search flex-align-center">
              <el-input
                v-model="name"
                placeholder="请输入姓名"
                class="input-name"
                clearable
                @keyup.enter="getAllEmp"
                @clear="getAllEmp"
              />
              <el-input
                v-model="telephone"
                placeholder="请输入手机号"
                maxlength="11"
                class="input-name"
                clearable
                @keyup.enter="getAllEmp"
                @clear="getAllEmp"
              />
              <div class="filter">
                <HButton type="primary" @click="getAllEmp">
                  <el-icon>
                    <Search />
                  </el-icon>
                  搜索
                </HButton>
              </div>
            </div>
          </div>
          <div class="table">
            <el-table
              border
              stripe
              resizable
              :data="tableData"
              style="position: absolute"
              height="100%"
              ref="tableList"
              @selection-change="handleChange"
            >
              <template #empty>
                <el-empty description="暂无数据" />
              </template>
              <!--多选-->
              <el-table-column type="selection" width="40" :selectable="checkDisable" />

              <!--序号-->
              <el-table-column
                show-overflow-tooltip
                type="index"
                :index="indexMethod"
                label="序号"
                width="50"
              />

              <!--职员姓名-->
              <el-table-column show-overflow-tooltip prop="name" label="职员姓名" min-width="120" />

              <!--职员手机-->
              <el-table-column show-overflow-tooltip prop="phone" label="职员手机" width="120" />

              <!--职员角色-->
              <el-table-column show-overflow-tooltip prop="role" label="职员角色" width="120" />

              <!--状态-->
              <el-table-column show-overflow-tooltip prop="name" label="角色状态" width="80">
                <template #default="scope">
                  <HStatus v-if="!scope.row.depart">在职</HStatus>
                  <HStatus v-if="scope.row.depart" type="info">离职</HStatus>
                </template>
              </el-table-column>

              <!--是否职员主管-->
              <!-- <el-table-column show-overflow-tooltip prop="manager" label="是否职员主管" width="100">
                <template #default="scope">
                  <span>
                    {{
        scope.row.manager == null ? '系统超管' : scope.row.manager ? '是' : '否'
      }}</span>
                </template>
              </el-table-column> -->

              <!--创建时间-->
              <el-table-column
                show-overflow-tooltip
                prop="createTime"
                label="创建时间"
                width="170"
              />

              <!--更新时间-->
              <el-table-column
                show-overflow-tooltip
                prop="updateTime"
                label="更新时间"
                width="170"
              />

              <!--最后登录-->
              <el-table-column
                show-overflow-tooltip
                prop="loginTime"
                label="最后登录"
                width="170"
              />

              <!--操作-->
              <el-table-column show-overflow-tooltip fixed="right" label="操作" width="100">
                <template #default="scope">
                  <el-space :size="0" :spacer="spacer">
                    <HLink v-if="scope.row.superAccount == false" @click="changeEmp(scope.row)"
                      >修改</HLink
                    >
                    <HLink @click="viewEmpDetail(scope.row)">详细</HLink>
                  </el-space>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <!--分页-->
          <div class="footer">
            <Pagination
              ref="pagination"
              :list_total="total"
              @size-change="getSizeList"
              @current-change="getNumList"
            />
          </div>
        </el-main>
      </div>

      <!-- 新增/编辑部门弹窗 -->
      <HModal v-model="addDialog" size="small">
        <template #header>
          <div class="my-header">
            <h3 class="title">{{ organizeDialogTitle }}</h3>
          </div>
        </template>
        <div v-loading="editLoading" element-loading-text="加载中...">
          <div class="form-text">
            <el-form
              label-width="80"
              ref="ruleFormRef"
              :rules="rules"
              :model="ruleForm"
              class="modal_form_content"
              @validate="handleFormValidate"
            >
              <!--部门名称-->
              <el-form-item
                label="部门名称"
                class="form_input_item"
                :class="{ error_form_item: !formValidateResult['name'] }"
                prop="name"
              >
                <el-input clearable v-model="ruleForm.name" placeholder="请输入名称" />
              </el-form-item>

              <!--上级部门-->
              <el-form-item
                label="上级部门"
                class="form_select_item"
                :class="{ error_form_item: !formValidateResult['level'] }"
                prop="level"
              >
                <el-select
                  v-model="ruleForm.level"
                  placeholder="请选择"
                  filterable
                  clearable
                  reserve-keyword
                  remote-show-suffix
                  :loading="organizeLoading"
                  :filter-method="searchOrganizeSelect"
                >
                  <el-option label="独立组织" value="0" />
                  <el-option
                    v-for="item in organizeSelect"
                    :label="item.name"
                    :disabled="item.id == ruleForm.id"
                    :value="item.id"
                    :key="item.id"
                  >
                    <span>{{ item.name }}</span>
                    <span v-show="item.system" class="organize-tip">
                      {{ item.system == true ? '系统组织' : '' }}
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>

              <!--部门主管-->
              <el-form-item
                label="部门主管"
                class="form_select_item"
                :class="{ error_form_item: !formValidateResult['manegerEmpId'] }"
                prop="manegerEmpId"
              >
                <el-select
                  v-model="ruleForm.manegerEmpId"
                  placeholder="请选择"
                  filterable
                  clearable
                  reserve-keyword
                  remote-show-suffix
                  :loading="empLoading"
                  :filter-method="searchEmpSelect"
                >
                  <el-option
                    v-for="item in empSelect"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>

        <template #footerLeft>
          <HPlainBgButton
            is-modal
            type="error"
            v-show="organizeDialogTitle === '编辑部门'"
            @click="deleOrganize"
            >删除
          </HPlainBgButton>
        </template>

        <template #footerRight>
          <HButton
            is-modal
            type="primary"
            @click="saveAddOrganize(ruleFormRef)"
            :loading="searchBtnLoading == true"
            >保存
          </HButton>
          <HButton is-modal @click="onAddOrEditDepartmentModalClose"> 取消 </HButton>
        </template>
      </HModal>

      <!-- 新增/修改职员弹窗 -->
      <HModal
        class="add-dialog2"
        v-model="addDialog2"
        width="400px"
        top="12vh"
        :draggable="true"
        :destroy-on-close="true"
        :close-on-click-modal="false"
      >
        <template #header>
          <div class="my-header">
            <h3 class="title">{{ empDialogTitle }}</h3>
          </div>
        </template>
        <div class="form-text" style="height: 220px">
          <el-form label-width="80" ref="empFormRef" :model="empForm" class="modal_form_content">
            <el-form-item
              label="手机号"
              class="form_input_item"
              prop="phone"
              :rules="[
                { required: true, message: '请输入正确的手机号', trigger: 'blur' },
                { validator: phone(empForm.phone), trigger: 'blur' },
              ]"
            >
              <div style="display: flex; gap: 5px; width: 100%">
                <el-input
                  v-model="empForm.phone"
                  class="item-input"
                  maxlength="11"
                  clearable
                  placeholder="请输入手机号"
                  @keyup.enter="searchEmp(empFormRef)"
                />
                <HPlainButton :loading="searchBtnLoading == true" @click="searchEmp(empFormRef)"
                  >查询</HPlainButton
                >
              </div>
            </el-form-item>

            <template v-if="showInfo">
              <!-- 密码 -->
              <el-form-item
                label="密码"
                class="form_input_item"
                prop="password"
                v-if="empForm.id == ''"
              >
                <el-input
                  placeholder="请输入密码"
                  clearable
                  v-model="empForm.password"
                  :type="passwordType"
                >
                  <template #suffix>
                    <div class="show-pwd" @click="showPwd">
                      <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
                    </div>
                  </template>
                </el-input>
              </el-form-item>

              <!-- 姓名 -->
              <el-form-item label="姓名" class="form_input_item" prop="name">
                <el-input v-model="empForm.name" clearable placeholder="请输入姓名" />
              </el-form-item>

              <!-- 昵称 -->
              <el-form-item label="昵称" class="form_input_item">
                <el-input v-model="empForm.nickname" clearable placeholder="请输入昵称" />
              </el-form-item>

              <!-- 所属部门 -->
              <el-form-item label="所属部门" class="form_select_item" prop="level">
                <el-select
                  v-model="empForm.level"
                  placeholder="请选择"
                  filterable
                  clearable
                  reserve-keyword
                  remote-show-suffix
                  :loading="organizeLoading"
                  :filter-method="searchOrganizeSelect"
                >
                  <el-option
                    v-for="item in organizeSelect"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  >
                    <span>{{ item.name }}</span>
                    <span v-show="item.system" class="organize-tip">
                      {{ item.system == true ? '系统组织' : '' }}
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>

              <!-- 职员角色 -->
              <el-form-item label="职员角色" class="form_select_item" prop="author">
                <el-select
                  v-model="empForm.author"
                  placeholder="请选择"
                  filterable
                  clearable
                  reserve-keyword
                  remote-show-suffix
                  :loading="roleLoading"
                  :filter-method="searchRoleSelect"
                >
                  <el-option
                    v-for="item in roleSelect"
                    :label="item.name"
                    :value="item.id"
                    :key="item.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="角色状态" class="form-item">
                <el-radio-group v-model="empForm.depart">
                  <el-radio :value="false">在职</el-radio>
                  <el-radio :value="true">离职</el-radio>
                </el-radio-group>
              </el-form-item>
            </template>
          </el-form>
        </div>

        <template #footerLeft>
          <HPlainBgButton
            is-modal
            type="error"
            v-show="empDialogTitle === '修改职员'"
            @click="deleEmp"
            >删除</HPlainBgButton
          >
        </template>

        <template #footerRight v-if="showInfo">
          <HButton is-modal type="primary" @click="saveAddEmp(empFormRef)">保存</HButton>
          <HButton is-modal @click="addDialog2 = false">取消</HButton>
        </template>
      </HModal>

      <!--职员信息弹窗-->
      <template v-if="currentVisibleEmp">
        <EmpDetailModal :info="(currentVisibleEmp as EmpDetail)" v-model="empDetailModalVisible" />
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ref, onMounted, reactive, markRaw, h } from 'vue'
  import { ElDivider, FormInstance } from 'element-plus'
  import { Search, Delete } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import {
    getOrganizeList,
    saveOrganize,
    getEmpList,
    saveEmp,
    getInfoAccount,
    rolePageSelecct,
    empPageSelecct,
    organizePageSelecct,
    getInfoOrganize,
    deleteOrganize,
    deleteEmp,
    getInfoEmp,
  } from '@/api/organize'
  import { phone, password } from '@/utils/validate'
  import EmpDetailModal from './components/EmpDetail.vue'
  import { EmpDetail } from './types'
  import _ from 'lodash'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HPlainBgButton from '@/components/common/button/HPlainBgButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import useFormValidateService from '@/service/common/useFormValidate/useFormValidateService'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.accountPermission.staffManger,
  })

  // 间距组件的间隔符
  const spacer = h(ElDivider, {
    direction: 'vertical',
    style: 'display: flex; align-items: center;',
  })

  // 职员详情弹窗状态
  const empDetailModalVisible = ref(false)

  const loading = ref(false) // 页面加载loading
  const defaultKey = ref('')

  const trees = ref([]) // 组织列表
  const organizeId = ref() // 组织ID
  const organizeIds = ref([]) // 组织ID集合

  // 部门表单数据
  const ruleForm = reactive({
    name: '', // 部门名称
    level: '', // 部门层级
    manegerEmpId: '', // 部门主管
    id: '',
  })

  // 表单元素
  const ruleFormRef = ref<FormInstance>()

  /**
   * 添加/编辑部分弹窗表单验证规则
   */
  const rules = reactive({
    name: [{ required: true, message: '请输入部门名称', trigger: ['blur', 'change'] }],
    level: [{ required: true, message: '请选择部门层级', trigger: ['blur', 'change'] }],
    manegerEmpId: [{ required: true, message: '请选择部门主管', trigger: ['blur', 'change'] }],
  })

  /**
   * 使用表单验证服务
   */
  const { handleFormValidate, resetFormValidateResult, formValidateResult } =
    useFormValidateService([
      { name: 'name', isSelect: false },
      { name: 'level', isSelect: false },
      { name: 'manegerEmpId', isSelect: false },
    ])

  /**
   * 编辑/添加部门弹窗关闭事件
   */
  const onAddOrEditDepartmentModalClose = () => {
    addDialog.value = false
    resetFormValidateResult()
  }

  const pagination = ref() // 分页dom
  const limit = ref() // 每页显示数量
  const page = ref() // 当面页码
  const total = ref() // 总数目

  // 搜索框
  const name = ref('') // 姓名
  const telephone = ref('') // 手机号

  const tableList = ref() // 列表dom
  const tableData = ref([]) // 组织职员列表
  const showInfo = ref(false)
  const searchBtnLoading = ref(false)

  const empFormRef = ref<FormInstance>()
  const empFormRef2 = ref<FormInstance>()

  // 职员表单数据
  const empForm = reactive({
    accountId: '', // 人员账号ID
    id: '', // 人员ID
    password: '', // 密码
    empId: '', // 职员ID
    name: '', // 姓名
    nickname: '', // 昵称
    phone: '', // 手机号
    level: '', // 部门层级
    author: '', // 角色
    loginTime: '',
    depart: false,
  })

  // 验证规则
  const empRules = reactive({
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { validator: password(empForm.password), trigger: 'blur' },
    ],
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    level: [{ required: true, message: '请选择所属部门', trigger: 'blur' }],
    author: [{ required: true, message: '请选择职员角色', trigger: 'blur' }],
  })

  const passwordType = ref('password')
  const showPwd = () => {
    if (passwordType.value === 'password') {
      passwordType.value = ''
    } else {
      passwordType.value = 'password'
    }
  }

  // 弹窗显示
  const addDialog = ref(false) // 添加组织
  const addDialog2 = ref(false) // 添加职员

  // 标题
  const organizeDialogTitle = ref('')
  const empDialogTitle = ref('')

  // 弹窗loading
  const editLoading = ref(false)

  const notAllow = ref(true) // 是否允许修改组织
  const parentId = ref() // 父级组织ID

  // 下拉数据
  const organizeSelect = ref() // 企业组织
  const empSelect = ref() // 企业职员
  const roleSelect = ref() // 企业角色

  // 搜索loading
  const organizeLoading = ref(false)
  const empLoading = ref(false)
  const roleLoading = ref(false)

  // 搜索值
  const empVal = ref('') // 组织
  const organizeVal = ref('') // 职员
  const roleVal = ref('') // 角色

  // 树型列表配置选项
  const defaultProps = {
    children: 'organizesVos',
    label: 'name',
  }

  // 列表序号
  const indexMethod = (index: number) => {
    return (index + 1) * 1
  }

  // 判断是否可选
  const checkDisable = (row) => {
    if (row.superAccount == true) {
      return false // 不可选
    } else {
      return true // 可选
    }
  }

  // 获取表格选中的数据
  const selecttion = ref([])
  const handleChange = (val: any) => {
    if (val.length != 0) {
      val.forEach((item) => {
        if (selecttion.value.indexOf(item.empId) == -1) {
          selecttion.value.push(item.empId)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.empId)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  // 获取组织列表
  const getAllOrganize = async () => {
    loading.value = true
    await getOrganizeList().then((res) => {
      trees.value = res.data.data.rows
      defaultKey.value = res.data.data.rows[0].id
      loading.value = false
    })
  }

  // 获取职员列表
  const getAllEmp = async () => {
    loading.value = true
    limit.value = pagination.value.size
    page.value = pagination.value.current
    const data = {
      limit: limit.value,
      name: name.value,
      organizeId: organizeId.value == undefined ? '' : organizeId.value,
      page: page.value,
      phone: telephone.value,
    }
    await getEmpList(data).then((res: any) => {
      total.value = parseInt(res.data.data.total)
      tableData.value = res.data.data.rows
      loading.value = false
    })
  }
  const isMounted = ref(false)
  onMounted(async () => {
    isMounted.value = true
    loading.value = true
    await getAllOrganize()
    await getAllEmp()
    loading.value = false
  })

  // 点击部门查找职员
  const handleNodeClick = (data) => {
    parentId.value = data.parentId
    defaultKey.value = data.id
    if (data.system == false) {
      organizeId.value = data.id
      notAllow.value = false
    } else {
      organizeId.value = ''
      notAllow.value = true
    }
    getAllEmp()
  }

  // 获取组织下拉数据
  const getOrganizeSelecct = async (n: string) => {
    organizeLoading.value = true
    const params = {
      name: n,
      limit: limit.value,
      page: page.value,
    }
    const res = await organizePageSelecct(params)
    organizeSelect.value = res.data.data.rows
    organizeLoading.value = false
  }

  // 搜索组织下拉数据
  const searchOrganizeSelect = _.throttle((query: string) => {
    if (organizeVal.value !== query) {
      organizeVal.value = query
      getOrganizeSelecct(organizeVal.value)
    }
  }, 500)

  // 获取职员下拉数据
  const getEmpSelecct = async (n: string) => {
    empLoading.value = true
    const params = {
      name: n,
      limit: limit.value,
      page: page.value,
    }
    const res = await empPageSelecct(params)
    empSelect.value = res.data.data.rows
    empLoading.value = false
  }

  // 搜索职员下拉数据
  const searchEmpSelect = _.throttle((query: string) => {
    if (empVal.value !== query) {
      empVal.value = query
      getEmpSelecct(empVal.value)
    }
  }, 500)

  // 获取角色下拉数据
  const getRoleSelecct = async (n) => {
    roleLoading.value = true
    const params = {
      name: n,
      limit: limit.value,
      page: page.value,
    }
    const res = await rolePageSelecct(params)
    roleSelect.value = res.data.data.rows
    roleLoading.value = false
  }

  // 搜索角色下拉数据
  const searchRoleSelect = _.throttle((query: string) => {
    if (roleVal.value !== query) {
      roleVal.value = query
      getRoleSelecct(roleVal.value)
    }
  }, 500)

  // 新增部门
  const addOrganize = () => {
    organizeDialogTitle.value = '新增部门'
    getOrganizeSelecct('')
    getEmpSelecct('')
    ruleForm.name = ''
    ruleForm.manegerEmpId = ''
    ruleForm.id = ''
    ruleForm.level = defaultKey.value
    addDialog.value = true
  }

  // 编辑部门
  const editOrganize = () => {
    organizeDialogTitle.value = '编辑部门'
    editLoading.value = true
    getOrganizeSelecct('')
    getEmpSelecct('')
    getInfoOrganize(defaultKey.value).then((res) => {
      ruleForm.name = res.data.data.row.name
      ruleForm.level = res.data.data.row.parentId
      ruleForm.manegerEmpId = res.data.data.row.manegerEmpId
      ruleForm.id = res.data.data.row.id
      editLoading.value = false
    })
    addDialog.value = true
  }

  // 保存部门
  const saveAddOrganize = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    const data = {
      manegerEmpId: ruleForm.manegerEmpId,
      name: ruleForm.name,
      parentId: ruleForm.level,
    }
    const data2 = {
      id: organizeId.value,
      manegerEmpId: ruleForm.manegerEmpId,
      name: ruleForm.name,
      parentId: ruleForm.level,
    }
    formEl.validate(async (valid) => {
      if (valid) {
        if (organizeDialogTitle.value == '编辑部门') {
          // 编辑
          saveOrganize(data2).then((res) => {
            if (res.data.success) {
              ElMessage({
                message: res.data.message,
                type: 'success',
                duration: 2000,
              })
              addDialog.value = false
              getAllOrganize()
              loading.value = false
            } else {
              if (res.data.isError)
                ElMessage({
                  message: res.data.message,
                  type: 'warning',
                  duration: 2000,
                })
              return
            }
          })
        } else {
          // 新增
          saveOrganize(data).then((res) => {
            if (res.data.success) {
              ElMessage({
                message: res.data.message,
                type: 'success',
                duration: 2000,
              })
              addDialog.value = false
              getAllOrganize()
              loading.value = false
            } else {
              if (res.data.isError)
                ElMessage({
                  message: res.data.message,
                  type: 'warning',
                  duration: 2000,
                })
              return
            }
          })
        }
      } else {
        return
      }
    })
  }

  // 删除部门
  const deleOrganize = () => {
    if (organizeIds.value.indexOf(organizeId.value) == -1) {
      organizeIds.value.push(organizeId.value)
    }
    ElMessageBox({
      type: 'error',
      icon: markRaw(Delete),
      title: '提示',
      message: '确认删除该部门?',
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      await deleteOrganize(organizeIds.value).then((res: any) => {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
      })
      addDialog.value = false
      getAllOrganize()
    })
  }

  // 添加职员
  const addEmp = () => {
    empDialogTitle.value = '新增职员'
    empForm.phone = ''
    empForm.author = ''
    empForm.depart = false
    showInfo.value = false
    getOrganizeSelecct('')
    getRoleSelecct('')
    empForm.level = defaultKey.value
    addDialog2.value = true
  }

  // 修改职员
  const changeEmp = (obj: any) => {
    getOrganizeSelecct('')
    getRoleSelecct('')
    empDialogTitle.value = '修改职员'
    showInfo.value = true
    empForm.id = obj.id
    empForm.phone = obj.phone
    empForm.name = obj.name
    empForm.nickname = obj.nickname
    empForm.empId = obj.empId
    empForm.level = defaultKey.value
    empForm.depart = obj.depart
    getInfoEmp(obj.empId).then((res) => {
      empForm.accountId = res.data.data.row.accountId
      empForm.author = res.data.data.row.roleId
    })
    addDialog2.value = true
  }

  // 查询职员相关信息
  const searchEmp = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validateField('phone', (valid) => {
      if (valid) {
        searchBtnLoading.value = true
        getInfoAccount(empForm.phone).then((res) => {
          showInfo.value = true
          searchBtnLoading.value = false
          empForm.id = res.data.data.id
          empForm.name = res.data.data.name
          empForm.accountId = res.data.data.id
        })
      } else {
        return false
      }
    })
  }

  // 保存职员
  const saveAddEmp = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    const data = {
      accountId: empForm.accountId,
      depart: empForm.depart,
      name: empForm.name,
      nickname: empForm.nickname,
      organizeId: empForm.level,
      password: empForm.password,
      phone: empForm.phone,
      roleId: empForm.author,
    }
    const data2 = {
      id: empForm.empId,
      accountId: empForm.accountId,
      name: empForm.name,
      nickname: empForm.nickname,
      organizeId: empForm.level,
      password: empForm.password,
      phone: empForm.phone,
      roleId: empForm.author,
      depart: empForm.depart,
    }
    formEl.validate(async (valid) => {
      if (valid) {
        if (empDialogTitle.value == '修改职员') {
          // 修改
          saveEmp(data2).then((res) => {
            if (res.data.success) {
              ElMessage({
                message: res.data.message,
                type: 'success',
                duration: 2000,
              })
              addDialog2.value = false
              getAllEmp()
              loading.value = false
            } else {
              if (res.data.isError)
                ElMessage({
                  message: res.data.message,
                  type: 'warning',
                  duration: 2000,
                })
              return
            }
          })
        } else {
          // 新增
          saveEmp(data).then((res) => {
            if (res.data.success) {
              ElMessage({
                message: res.data.message,
                type: 'success',
                duration: 2000,
              })
              addDialog2.value = false
              getAllEmp()
              loading.value = false
            } else {
              if (res.data.isError)
                ElMessage({
                  message: res.data.message,
                  type: 'warning',
                  duration: 2000,
                })
              return
            }
          })
        }
      } else {
        return
      }
    })
  }

  // 当前查看的职员信息
  const currentVisibleEmp = ref<null | EmpDetail>(null)

  // 查看职员详细
  const viewEmpDetail = (obj: EmpDetail) => {
    currentVisibleEmp.value = { ...obj }
    empDetailModalVisible.value = true
  }

  // 删除职员
  const deleEmp = () => {
    let tmp = []
    tmp.push(empForm.empId)
    ElMessageBox({
      type: 'error',
      icon: markRaw(Delete),
      title: '提示',
      message: '确认删除该职员?',
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(async () => {
      await deleteEmp(tmp, defaultKey.value).then((res: any) => {
        ElMessage({
          message: res.data.message,
          type: 'success',
          duration: 2000,
        })
      })
      addDialog2.value = false
      getAllEmp()
    })
  }

  // 显示数量改变时
  const getSizeList = () => {
    getAllEmp()
  }

  // 页码改变时
  const getNumList = () => {
    getAllEmp()
  }
</script>

<style scoped lang="scss">
  @import './index';
</style>
